//
//  CycleView.swift
//  DouYu
//
//  Created by 王鹏宇 on 2018/4/12.
//  Copyright © 2018年 王鹏宇. All rights reserved.
//

import UIKit

private let KCycleCellID = "KCycleCellID"

class CycleView: UIView {

    //MARK: 懒加载
    fileprivate lazy var collectionView : UICollectionView = {
        [weak self] in
        //[weak self] 和  [unowned self] 按照定义，两者都是用来解决引用循环的。若self在closure调用的生命周期一直存在，使用unowned，若self在closure调用时可能已经被deinit或置为nil，则使用weak。在Swift中，weak self会被当做一个Optional<Self>类型来处理。
        
       //在closure 调用 self用法不一样
        // [weak self]     layout.itemSize = (self?.bounds.size)!
        // [unowned self]  layout.itemSize = (self.bounds.size)
        
        //创建布局
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = (self?.bounds.size)!
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .horizontal
        //创建UICollectionView
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        collectionView.dataSource = self;
        collectionView.delegate = self;
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.isPagingEnabled = true
        collectionView.bounces = false
        
        // 注册Cell
        collectionView.register(UINib(nibName: "CollectionCycleCell", bundle: nil), forCellWithReuseIdentifier: KCycleCellID)
        
        return collectionView;

    }()
    
    fileprivate lazy var pageControl: UIPageControl = {
       
        let pageControl = UIPageControl()
        //pageControl.delete(self)
        
        return pageControl
    }()
    
    var cycleTimer : Timer?
    var cycleModels : [CycleModel]?{
        didSet {
           
            //刷新collectionView
            collectionView.reloadData()
            
            //设置pageControl个数
            pageControl.numberOfPages = cycleModels?.count ?? 0
            
            //默认滚到中间某个位置
            let indexPath = IndexPath(item: (cycleModels?.count ?? 0) * 100, section: 0)
            collectionView.scrollToItem(at: indexPath, at: .left, animated: false)
            //添加定时器
            removerCycleTimer()
            addCycleTimer()
        }
    }
    
    
    //MARK:- 自定义构造函数
    override init(frame: CGRect) {
      
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}

// MARK:-初始化UI
extension CycleView {
    
    fileprivate func setupUI() {
        
        collectionView.frame = bounds
        addSubview(collectionView)
        
        pageControl.frame = CGRect(x: bounds.size.width - 130, y: bounds.height - 30, width: 120, height: 25)
        addSubview(pageControl)
    }
}

// MARK:- 遵守 UICollectionViewDataSource 协议

extension CycleView : UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return (cycleModels?.count ?? 0) * 10000
    }
   
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: KCycleCellID, for: indexPath) as! CollectionCycleCell
        
        cell.cycleModel = cycleModels![(indexPath as NSIndexPath).item % cycleModels!.count]
        
        return cell
    }
    
    
}

// MARK: - 遵守 UICollectionViewDelegate 协议

extension CycleView : UICollectionViewDelegate {
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        //获取滚动的偏移量
        let offsetX = scrollView.contentOffset.x + scrollView.bounds.width * 0.5
        
        //计算pageControl的currentIndex
        pageControl.currentPage = Int(offsetX / scrollView.bounds.width) % (cycleModels?.count ?? 1)
        
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        
        removerCycleTimer()
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        
        addCycleTimer()
    }
    
}


// MARK:- 定时器 操作

extension CycleView  {
    
    fileprivate func addCycleTimer() {
        cycleTimer = Timer(timeInterval: 3.0, target: self, selector: #selector(self.scrollToNext), userInfo: nil, repeats: true)
        RunLoop.main.add(cycleTimer!, forMode: RunLoopMode.commonModes)
    }
    
    fileprivate func removerCycleTimer() {
        
        cycleTimer?.invalidate()//从运用循环中移除
        cycleTimer = nil
    }
    
    @objc fileprivate func scrollToNext() {
        //获取滚动偏移
        let currentOffsetX  = collectionView.contentOffset.x
        let offsetX = currentOffsetX + collectionView.bounds.width
        
        //滚动位置
        collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true)
    }
}
